import Utils from "../../../Utils";
import Howitzer from "../../flyer/DestructibleFlyer/FlyerMissile/Howitzer";
import { Killer } from "../../funcObj/interface/HealthPoint";
import { Location } from "../../info/Predefine";
import GameManager from "../../manager/GameManager";
import NodePoolManager from "../../manager/NodePoolManager";
import Player from "../../player/Player";
import LaunchableFalicity from "../LaunchableFalicity";

const { ccclass, property } = cc._decorator;

/**
 * 榴弹炮基地
 */
@ccclass
export default class HowitzerBase extends LaunchableFalicity {

    @property(cc.Node)
    points: cc.Node = null;

    /**
     * 当前数量
     */
    howitzerCount: number = 0;
    creating: boolean;

    get count(): number {
        return this.howitzerCount;
    }

    init(player: Player): void {
        super.init(player);
        let animaComp = this.getComponentInChildren(cc.Animation);
        let clipName = animaComp.getClips()[player.playerId].name;
        animaComp.play(clipName);
        this.creating = false;
        this.creat();
    }

    creat() {
        if (this.creating) return;
        this.CreatingProgress.progress = 0;
        this.CreatingProgress.node.active = true;
        this.creating = true;
        cc.tween(this.CreatingProgress)
            .to(this.makingTime, { progress: 1 })
            .call(() => {
                this.howitzerCount++;
                this.player.node.emit(Player.EventType.更新飞行物数量, this.facilityType, 1);
            }).call(() => {
                this.CreatingProgress.node.active = false;
                this.creating = false;
                if (this.howitzerCount < this.facilityInfo.每基地可制造上限) {
                    this.creat();
                }
            })
            .start();
    }

    dispatch(target: Location) {
        super.dispatch(target);
        this.howitzerCount--;
        this.player.node.emit(Player.EventType.更新飞行物数量, this.facilityType, -1);

        let bullet = NodePoolManager.instance.obtain(NodePoolManager.instance.howitzerBullet);
        let flyerParent = this.player.flyerParentNode;
        let spacePosition = this.points.children[this.howitzerCount].convertToWorldSpaceAR(cc.Vec3.ZERO);
        this.dispatchQueue.push({
            flyer: bullet, target: target, dispatchFunc: (target) => {
                bullet.parent = flyerParent;
                bullet.position = flyerParent.convertToNodeSpaceAR(spacePosition);
                bullet.getComponent(Howitzer).init(this, target);
            }
        })

        this.creat();
    }

    die(killer: Killer): void {
        super.die(killer);
        this.howitzerCount = 0;
        cc.Tween.stopAllByTarget(this.CreatingProgress);
    }
}
